package com.sunsharing.transport.mina;

import com.sunsharing.common.URL;
import com.sunsharing.common.anno.Factory;
import com.sunsharing.transport.Channel;
import com.sunsharing.transport.ConnectClients;
import com.sunsharing.transport.Server;
import com.sunsharing.transport.IoHandle;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-3-31
 * Time: 下午3:29
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="MINA")
public class MinaServer  implements Server {

    Logger logger = Logger.getLogger(MinaServer.class);

    /** 监听连接的对象 */
    private IoAcceptor acceptor;
    //MINA://domain.IP:port?proName=abc
    public void startServer(URL url,IoHandle ioHandle) {
        InetSocketAddress socketAddress = new InetSocketAddress(url.getPort());
        MinaIoHandler ioHandler = new MinaIoHandler(ioHandle,false,url);
        try {
            logger.info("Mina开始" + socketAddress.getPort() + "启动监听...");

            acceptor = new NioSocketAcceptor();

            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);


            acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(new MyProtocolCodecFactory()));
            // 绑定监听
            //acceptor.bind(socketAddress, serverIoHandler, cfg);
            acceptor.setHandler(ioHandler);

            acceptor.bind(socketAddress);

            logger.info("启动监听完毕...");

        } catch (IOException e) {
            logger.error("启动监听的时候出错!", e);
            throw new RuntimeException("启动监听的时候出错!");
        } catch (RuntimeException e) {
            logger.error("运行监听的时候出错!", e);
            throw new RuntimeException("运行监听的时候出错!");
        } catch (Exception e) {
            logger.error("运行监听的时候出错!", e);
            throw new RuntimeException("运行监听的时候出错!");
        }
    }



    public void stopServer()
    {
        acceptor.dispose();
    }

}
